package top.yqingyu.trans$client.main;

import lombok.extern.slf4j.Slf4j;
import top.yqingyu.qymsg.QyMsg;
import top.yqingyu.trans$client.api.Connection;
import top.yqingyu.trans$client.api.ConnectionConfig;
import top.yqingyu.trans$client.api.ConnectionFactory;

import java.util.Scanner;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author YYJ
 * @version 1.0.0
 * @date 2022/4/22 4:19
 * @description
 * @modified by
 */
@Slf4j
public class TransClient {
    public ConnectionConfig clientConf;
    public ConnectionFactory factory;

    TransClient(ConnectionConfig config) throws Exception {
        clientConf = config;
        this.factory = new ConnectionFactory(config);
    }

    public final LinkedBlockingQueue<QyMsg> REQ_MSG_QUEUE = new LinkedBlockingQueue<>();
    public final LinkedBlockingQueue<QyMsg> RSP_MSG_QUEUE = new LinkedBlockingQueue<>();
    public final ConcurrentHashMap<String, QyMsg> RCV_MSG_CONTAINER = new ConcurrentHashMap<>();
    public final AtomicBoolean running = new AtomicBoolean(true);
    public final ReentrantLock readMsgLock = new ReentrantLock();


    public static void main(String[] args) throws Exception {
        ConnectionConfig build = new ConnectionConfig.Builder(ConnectionConfig.Type.FILE)
                .Pool_max(1)
                .Pool_min(1)
                .build();
        TransClient client = new TransClient(build);
        HeartBeatThread.init(client);
        SendMsgThread.init(client);
        ReadMsgThread.init(client);
        PrintMsgThread.init(client);
        ClientInteractionThread.init(client);
        Scanner scanner = new Scanner(System.in);
        while (client.running.get()) {
            try {
                System.out.print("$>");
                String msg = scanner.nextLine();
                QyMsg clone = client.clientConf.NORMAL_MSG.clone();
                clone.putMsg(msg);
                client.REQ_MSG_QUEUE.add(clone);
            } catch (Exception e) {
                log.error("", e);
            }

        }
    }

    public Connection getConnection() throws Exception {
        return factory.getConnection();
    }
}
